from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, RetrieveAPIView, UpdateAPIView

from meiduo_admin.serializers.orders import OrderListSerializer, OrderInfoSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo


class OrderListView(ListAPIView):
    """获取订单表数据"""
    serializer_class = OrderListSerializer
    # 分页类
    pagination_class = PageNum

    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return OrderInfo.objects.all().order_by('order_id')

        else:
            return OrderInfo.objects.filter(order_id__contains=keyword).order_by('order_id')
    # 管理员权限
    # permission_classes = [IsAdminUser]


# 获取订单表详情数据
class OrderInfoView(RetrieveAPIView):
    # 序列化器
    serializer_class = OrderInfoSerializer

    def get_queryset(self):
        # 获取数据
        order_id = self.kwargs['pk']
        # 返回查询集
        return OrderInfo.objects.filter(order_id=order_id).order_by('order_id')


# 更新订单表状态数据
class OrderStateView(UpdateAPIView):

    def update(self, request, *args, **kwargs):
        # 获取数据
        order_id = kwargs['order_id']
        status = request.data.get('status')

        # 更新数据
        OrderInfo.objects.filter(order_id=order_id).update(status=status)

        # 返回响应
        return Response({'order_id': order_id, 'status': status})
